using System;
using System.Collections.Generic;
using System.Linq;
using VoiceAd.Models;
using System.Web.Security;
using System.Data.Linq.SqlClient;

namespace VoiceAd.DAL
{
    public class BookingRepository : IBookingRepository, IDisposable
    {
        private dbVoiceAdDataContext context = new dbVoiceAdDataContext();

        public BookingRepository(dbVoiceAdDataContext db)
        {
            this.context = db;
        }

        public IEnumerable<tblBooking> GetListBookings()
        {
            return context.tblBookings.ToList();
        }

        public IEnumerable<tblBooking> GetListBookingsByCampId(int campId)
        {
            return context.tblBookings.Where(x => x.CampaignId == campId).ToList();
        }

        public IEnumerable<tblBooking> GetListBookingsByCampIdAndStationName(int campId, string lStationName)
        {
            IEnumerable<tblBooking> lst = from a in context.tblBookings
                                          where SqlMethods.Like(a.tblStation.StationName, "%" + lStationName + "%") && a.CampaignId == campId
                                          select a;

            return lst;
        }

        public tblBooking GetBookingById(int id)
        {
            return context.tblBookings.Where(x => x.Id == id).FirstOrDefault();
        }

        public tblBooking GetBookingByCampId(int campId, int stationId)
        {
            return context.tblBookings.Where(x => x.CampaignId == campId && x.StationId == stationId).FirstOrDefault();
        }

        public void InsBooking(tblBooking tblbooking)
        {
            context.tblBookings.InsertOnSubmit(tblbooking);
            context.SubmitChanges();
        }

        public void UpdBooking(tblBooking tblbooking)
        {
            tblBooking obj = context.tblBookings.Where(x => x.Id == tblbooking.Id).First();
            obj.CampaignId = tblbooking.CampaignId;
            obj.StationId = tblbooking.StationId;
            obj.Title = tblbooking.Title;
            obj.Duration = tblbooking.Duration;
            context.SubmitChanges();
        }

        public void DelBooking(int id)
        {
            tblBooking obj = context.tblBookings.Single(x => x.Id == id);
            context.tblBookings.DeleteOnSubmit(obj);
            context.SubmitChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
